import os;

def is_module(dir_name):
	if os.path.isdir(dir_name):
		for content_name in os.listdir(dir_name):
			if content_name.endswith(".iml"):
				return True;
	return False;

def is_build_configured(module_dir_name):
	build_xml = os.path.join(module_dir_name,"build.xml");
	return os.path.exists(build_xml);
	

def put_file(dir_name, file_name, body, do_overwrite):
	full_file_name = os.path.join(dir_name,file_name);
	if not do_overwrite and os.path.exists(full_file_name):
		print("  %s exists, keeping as is" % file_name);
	else:
		out_file = open(full_file_name,"w");
		out_file.write(body);
		out_file.close();
		print("  created:",file_name);

def put_build_xml(module_dir_name, do_overwrite):
	template = ("""
<?xml version="1.0" encoding="utf-8"?>                    
<project name="%s" basedir="..">
    <import file="${basedir}/${ant.project.name}/${ant.project.name}-path.xml"/>
    <import file="${basedir}/${ant.project.name}/${ant.project.name}.xml"/>
</project>
""" % module_dir_name).strip()+"\n";
	put_file(module_dir_name, "build.xml",template,do_overwrite);

def put_module_path(module_dir_name, do_overwrite):
	template  = ("""
<?xml version="1.0" encoding="utf-8"?>
<project  basedir="..">
    <path id="path.%s.prod.id">
    </path>
</project>
""" % module_dir_name).strip()+"\n";
	put_file(module_dir_name, module_dir_name+"-path.xml",template,do_overwrite);

def put_module_xml(module_dir_name, do_overwrite):
	template=("""
<?xml version="1.0" encoding="utf-8"?>
<project basedir="..">
    <import file="${basedir}/module-impl.xml"/>

    <path id="path.compile.prod.id">
        <path refid="path.%s.prod.id"/>
    </path>
</project>
""" % module_dir_name).strip()+"\n";
	put_file(module_dir_name, module_dir_name+".xml",template,do_overwrite);
	
	
do_overwrite = False;

for dir_name in os.listdir('.'):
	if is_module(dir_name):
		print("Processing module: ",dir_name);
		if is_build_configured(dir_name):
			print("  OK (already configured)");
		else:
			print("  Adding build scripts...");
			put_build_xml(dir_name, do_overwrite);
			put_module_path(dir_name, do_overwrite);
			put_module_xml(dir_name, do_overwrite);
		
for dir_name in os.listdir('.'):
	if is_module(dir_name):
		print('<subant target="dist" antfile="${basedir}/'+dir_name+'/build.xml"/>');
		
